package cn.amaake.magicplugin.nacos.autoconfigure;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import cn.amaake.magicplugin.nacos.util.NacosConfigLoader;
import cn.amaake.magicplugin.nacos.util.NacosConfigPropertiesUtils;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;


public class NacosConfigEnvironmentProcessor implements EnvironmentPostProcessor, Ordered {

    private final Logger logger = LoggerFactory.getLogger(NacosConfigEnvironmentProcessor.class);
    private NacosConfig nacosConfigProperties;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        nacosConfigProperties = NacosConfigPropertiesUtils.buildNacosConfigProperties(environment);
        if (enable()) {
            logger.info("[Nacos Config Boot] : The preload log configuration is enabled");
            try {
                loadConfig(environment);
            } catch (NacosException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void loadConfig(ConfigurableEnvironment environment) throws NacosException {
        NacosConfigLoader configLoader = new NacosConfigLoader(nacosConfigProperties, environment);
        configLoader.loadConfig();
    }

    boolean enable() {
        return nacosConfigProperties != null && nacosConfigProperties.isEnableConfig();
    }

    // Do not set the minimum priority for future expansion needs

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 5;
    }


}
